import ctypes
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime

# 加载C库
lib = ctypes.CDLL('./libweather.so')

# 定义C结构体
class WeatherData(ctypes.Structure):
    _fields_ = [
        ("date", ctypes.c_char * 20),
        ("temp_high", ctypes.c_float),
        ("temp_low", ctypes.c_float),
        ("weather_day", ctypes.c_char * 20),
        ("weather_night", ctypes.c_char * 20)
    ]

# 设置函数原型
lib.process_csv.argtypes = [
    ctypes.c_char_p,
    ctypes.POINTER(ctypes.POINTER(WeatherData)),
    ctypes.POINTER(ctypes.c_int)
]
lib.process_csv.restype = None

def c_to_python_data(filename):
    data_ptr = ctypes.POINTER(WeatherData)()
    count = ctypes.c_int()

    lib.process_csv(filename.encode(), ctypes.byref(data_ptr), ctypes.byref(count))

    results = []
    for i in range(count.value):
        item = data_ptr[i]
        results.append({
            '日期': item.date.decode('utf-8'),
            '最高气温': item.temp_high,
            '最低气温': item.temp_low,
            '天气状况(白天)': item.weather_day.decode('utf-8'),
            '天气状况(夜间)': item.weather_night.decode('utf-8')
        })

    return pd.DataFrame(results)

# 温度趋势可视化
def plot_temperature_trend(df):
    plt.figure(figsize=(12, 6))
    plt.plot(df['日期'], df['最高气温'], 'r-', label='最高气温')
    plt.plot(df['日期'], df['最低气温'], 'b-', label='最低气温')
    plt.fill_between(df['日期'], df['最低气温'], df['最高气温'], color='gray', alpha=0.2)
    plt.title('全年温度趋势')
    plt.xticks(rotation=45)
    plt.legend()
    plt.tight_layout()
    plt.show()